package co.yixiang.yshop.framework.mq.redis.core;

import co.yixiang.yshop.framework.mq.redis.core.stream.AbstractRedisStreamMessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Redis Stream 健康检查器
 * 
 * @author yshop
 */
@Slf4j
@Component
public class RedisStreamHealthChecker {

    private final RedisMQTemplate redisMQTemplate;
    private final List<AbstractRedisStreamMessageListener<?>> streamListeners;

    public RedisStreamHealthChecker(RedisMQTemplate redisMQTemplate, 
                                  List<AbstractRedisStreamMessageListener<?>> streamListeners) {
        this.redisMQTemplate = redisMQTemplate;
        this.streamListeners = streamListeners;
    }

    /**
     * 应用启动完成后，检查所有Stream的健康状态
     */
    @EventListener(ApplicationReadyEvent.class)
    public void checkStreamHealth() {
        if (streamListeners.isEmpty()) {
            log.info("[RedisStreamHealthChecker][没有发现Stream监听器，跳过健康检查]");
            return;
        }

        log.info("[RedisStreamHealthChecker][开始检查{}个Stream的健康状态]", streamListeners.size());
        
        RedisTemplate<String, ?> redisTemplate = redisMQTemplate.getRedisTemplate();
        int successCount = 0;
        int failCount = 0;

        for (AbstractRedisStreamMessageListener<?> listener : streamListeners) {
            String streamKey = listener.getStreamKey();
            String groupName = listener.getGroup();
            
            boolean exists = RedisStreamInitializer.checkStreamAndGroupExists(redisTemplate, streamKey, groupName);
            if (exists) {
                log.info("[RedisStreamHealthChecker][Stream({}) 和 Consumer Group({}) 状态正常]", streamKey, groupName);
                successCount++;
            } else {
                log.warn("[RedisStreamHealthChecker][Stream({}) 或 Consumer Group({}) 状态异常，尝试重新初始化]", streamKey, groupName);
                boolean success = RedisStreamInitializer.safeCreateStreamAndGroup(redisTemplate, streamKey, groupName);
                if (success) {
                    log.info("[RedisStreamHealthChecker][Stream({}) 重新初始化成功]", streamKey);
                    successCount++;
                } else {
                    log.error("[RedisStreamHealthChecker][Stream({}) 重新初始化失败]", streamKey);
                    failCount++;
                }
            }
        }

        log.info("[RedisStreamHealthChecker][健康检查完成，成功: {}, 失败: {}]", successCount, failCount);
        
        if (failCount > 0) {
            log.error("[RedisStreamHealthChecker][发现{}个Stream初始化失败，请检查Redis连接和配置]", failCount);
        }
    }
} 